package com.competition.system.controller;

import com.competition.system.pojo.Race;
import com.competition.system.service.RaceService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 赛事管理
 * @author Lyq
 * @version 1.0
 * @create 2020/12/17 14:18
 */
@RestController
@RequestMapping("/race/")
public class RaceController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RaceController.class);

    @Autowired
    private RaceService raceService;

    @ApiOperation("查询赛事列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public List<Race> queryRaceList() {
        List<Race> raceList = new ArrayList<>();
        try {
            raceList = raceService.queryRaceList();
        }catch (Exception e){
            LOGGER.error("服务异常", e);
        }
        return raceList;
    }

    @ApiOperation("新增赛事")
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public Race addRace(@RequestBody Map<String, String> params){
        Race race = new Race();
        String id = String.valueOf(UUID.randomUUID());
        try {
            race.setId(id);
            race.setDate(transDate(Long.parseLong(params.get("date"))));
            race.setTitle(params.get("title"));
            race.setDescription(params.get("description"));
            race.setLevel(params.get("level"));
            race.setLocation(params.get("location"));
            race.setSponsor(params.get("sponsor"));
            race.setType(params.get("type"));
            return raceService.addRace(race);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return race;
    }

    private Date transDate(String dateStr) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Date date = simpleDateFormat.parse(dateStr);
        return date;
    }

    private Date transDate(Long times){
        return new Date(times);
    }

}
